'use strict'
const nodeCall = require('./nodeCall')
const events = require('events')


//会话类(子节点连接类)
class Node extends events.EventEmitter {
    constructor(nId, socket) {
        super()
        this.id = nId
        this.type = null
        this.name = ''
        this.socket = socket
        this.reqId = 0
        this.callbacks = {}
        this.handleSocket(socket)
    }

    handleSocket(socket) {
        let self = this
        socket.on('message', function(data) {
          console.log(data)
            data = JSON.parse(data)
            let reqId = data.reqId
            if (reqId && self.callbacks[reqId]) {
                self.callbacks[reqId](data.err, data.msg)
                delete self.callbacks[reqId]
            } else {
                let remoteFunc = nodeCall.getCall(data.route)
                remoteFunc(self, data.msg)
            }
        })
        socket.on('close', function(data) {
            console.info(`子节点${self.name}连接关闭`)
            self.emit('close', {
                id: self.id
            })
        })
        socket.on('error', function(data) {
            this.emit('close')
        })
    }

    //发送消息给子节点
    send(uId, route, msg, cb) {
        this.reqId += 1
        let data = {
            reqId: this.reqId,
            route: route,
            uId: uId,
            msg: msg
        }
        this.callbacks[this.reqId] = cb
        let sendData = JSON.stringify(data)
        this.socket.send(sendData)
    }

    close() {
        this.socket.close()
    }
}

module.exports = Node
